package client;

import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;

import client.ClientLib.ClientType;

public class PubFile {

	private static final int BLOCK_SIZE = 1024;
	private static final int HEADER_SIZE = 124 + 14;

	public static void main(String[] args) {
		String filename = args.length > 0 ? args[0] : "bitmapl.bmp";
		String host = args.length > 1 ? args[1] : "localhost";
		int port = args.length > 2 ? Integer.parseInt(args[2]) : 15000;
		String pubId = args.length > 3 ? args[3] : "file";
		
		System.out.printf("Publishing '%s' to %s:%d with name '%s'.\n", filename, host, port, pubId);
		
		File f = new File(filename);
		FileInputStream fin = null;
		long length = f.length();

		try {
			ClientLib client = new ClientLib(pubId, host, port, ClientType.PUBLISHER);
			client.connect();
			Thread.sleep(5000);
			fin = new FileInputStream(f);
			long off = 0;
			byte[] buf = new byte[BLOCK_SIZE];
			int readBytes = 0;
			long start = System.currentTimeMillis();
			byte[] header = new byte[HEADER_SIZE];
			while ((readBytes = fin.read(buf)) != -1) {
				if (off == 0) {
					System.arraycopy(buf, 0, header, 0, HEADER_SIZE);
				}
				ByteBuffer bb = ByteBuffer.allocate(16 + HEADER_SIZE + readBytes);
				bb.putLong(length);
				bb.putLong(off);
				bb.put(header);
				bb.put(buf, 0, readBytes);
				client.publish(bb.array());
				
				off += readBytes;
				Thread.sleep(1,500000);
			}
			System.out.println("Sent: " + client.getSeq() + " (" + (System.currentTimeMillis() - start) + " msec)");
			fin.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
